package com.aliyun.messagemgt.service;

import com.alibaba.csb.sdk.ContentBody;
import com.alibaba.csb.sdk.HttpCaller;
import com.alibaba.csb.sdk.HttpCallerException;
import com.alibaba.csb.sdk.HttpParameters;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.messagemgt.common.enums.PushResultEnum;
import com.aliyun.messagemgt.common.convert.MsgPushVOConverter;
import com.aliyun.messagemgt.common.dto.send.MsgMiddleResult;
import com.aliyun.messagemgt.common.dto.send.MsgRecordVO;
import com.aliyun.messagemgt.common.dto.send.PushChannelInfo;
import com.aliyun.messagemgt.common.enums.ChannelTypeEnum;
import com.aliyun.messagemgt.common.dto.send.SystemMsgPushDTO;
import com.aliyun.messagemgt.sendplugin.SendStrategy;
import com.aliyun.messagemgt.sendplugin.SendStrategyFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author byp
 * @date 2020/4/10
 */
@Service
public class SystemCsbMsgSendStrategy implements SendStrategy, InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(SystemCsbMsgSendStrategy.class);

    @Override
    public void afterPropertiesSet() {
        SendStrategyFactory.register(ChannelTypeEnum.SYSTEM.getType(), this);
    }


    @Override
    public void sendMessage(PushChannelInfo pushChannelInfo, MsgRecordVO msgRecordVO) {
        //服务名
        String apiName = pushChannelInfo.getApiName();
        //IP地址 http://CSB服务地址:8086/CSB
        String apiUrl = pushChannelInfo.getApiUrl();
        String method = pushChannelInfo.getMethod();
        //注：该字段为版本号
        String apiHost = pushChannelInfo.getApiHost();
        String apiAppKey = pushChannelInfo.getApiAppKey();
        String apiAppSecret = pushChannelInfo.getApiAppSecret();

        logger.info("系统端push基本参数为：apiName：{}, apiUrl:{}, method:{}, apiHost:{}, apiAppKey:{}, apiAppSecret:{}",
                apiName, apiUrl, method, apiHost, apiAppKey, apiAppSecret);

        HttpParameters.Builder builder = new HttpParameters.Builder();
        // 设置请求的URL。其中，CSB服务地址即创建该实例时绑定的SLB的地址。
        builder.requestURL(StringUtils.trim(apiUrl))
                // 设置服务名
                .api(apiName)
                // 设置版本号
                .version(apiHost)
                //设置调用方式, get/post
                .method(method);
        // 设置HTTP JSON表单请求参数
        SystemMsgPushDTO systemMsgPushDTO = MsgPushVOConverter.INSTANCE.msgRecordVO2systemMsgPushDTO(msgRecordVO);
        logger.info("系统端渠道消息推送body：{}", JSONObject.toJSONString(systemMsgPushDTO));
        ContentBody body = new ContentBody(JSONObject.toJSONString(systemMsgPushDTO));
        builder.contentBody(body);
        // 设置请求头
        builder.putHeaderParamsMap("appKey",apiAppKey);
        builder.putHeaderParamsMap("appSecret",apiAppSecret);
        List<MsgMiddleResult> results = msgRecordVO.getResults();
        try {
            String ret = HttpCaller.invoke(builder.build());
            logger.info("调用阿里接口返回ret：{}", ret);
            JSONObject retJson = JSONObject.parseObject(ret);
            Boolean success = retJson.getBoolean("success");
            if (Objects.nonNull(success) && success) {
                MsgMiddleResult msgMiddleResult = new MsgMiddleResult().setPushResultCode(PushResultEnum.PUSH_SUCCESS.getErrorCode())
                        .setPushResultDescription(PushResultEnum.PUSH_SUCCESS.getDescription()).setReceivers(msgRecordVO.getReceivers());
                results.add(msgMiddleResult);
            } else {
                String errMsg;
                if (Objects.isNull(success)) {
                    errMsg = retJson.getString("error");
                } else {
                    errMsg = retJson.getString("errMessage");
                }
                MsgMiddleResult msgMiddleResult = new MsgMiddleResult().setPushResultCode(PushResultEnum.SYSTEM_PUSH_ERROR.getErrorCode())
                        .setPushResultDescription(errMsg).setReceivers(msgRecordVO.getReceivers());
                results.add(msgMiddleResult);
            }
        } catch (HttpCallerException e) {
            logger.error("系统端消息推送异常", e);
            MsgMiddleResult msgMiddleResult = new MsgMiddleResult().setPushResultCode(PushResultEnum.SYSTEM_PUSH_ERROR.getErrorCode())
                    .setPushResultDescription(PushResultEnum.SYSTEM_PUSH_ERROR.getDescription()).setReceivers(msgRecordVO.getReceivers());
            results.add(msgMiddleResult);
        }
    }
}
